//
//  ThreadViewsController.m
//  ViewPoint
//
//  Created by Demiao Lin on 09-2-22.
//  Copyright 2009 Tsinghua. All rights reserved.
//

#import "ThreadViewController.h"

#import "Setting.h"

#define INDICATOR_VIEW          999
#define TOOLBAR_VIEW            998

#define kleftTransparentView    997
#define krightTransparentView   996
#define kcenterTransparentView  995

@implementation ThreadTransparentView

@synthesize controller;
@synthesize touchType;

//- (void) didMoveToSuperview {
    // this hook method is used to initialize the view; we don't want 
    // any user input to be delivered to the UIWebView, instead, the 
    // MapView overlay will receive all input and convert it to commands 
    // that can be performed by the Google Maps Javascript API directly
    
    //self.userInteractionEnabled = NO;
//}

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
    /*
    UIAlertView *alert = [[[UIAlertView alloc] initWithTitle:@"Debug 1"
                                                     message:@"Touch in transparent view Began!"
                                                    delegate:nil
                                           cancelButtonTitle:@"Dismiss"
                                           otherButtonTitles:nil] autorelease];
    [alert show];
    
    
    if(self.superview){
        [self.superview touchesBegan:touches withEvent:event];
    }
    */
	touchType = 0;
    self.backgroundColor = [UIColor colorWithHue:0.0 saturation:0.0 brightness:1.0 alpha:0.2];
}

- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event {
    self.backgroundColor = [UIColor clearColor];
    if(self.tag==kleftTransparentView){
        if(controller && touchType>=0){
            //[controller goToThreadPrevious:nil];
        }
    }else if(self.tag==krightTransparentView){
        if(controller && touchType>=0){
            //[controller goToThreadNext:nil];
        }
    }else if(self.tag==kcenterTransparentView){
        if(controller && touchType>=0){
            [controller toggleToolbarAndNavBar];
        }
    }
    /*
    if(self.superview){
        [self.superview touchesEnded:touches withEvent:event];
    }
    */
}

- (void)touchesCancelled:(NSSet *)touches withEvent:(UIEvent *)event {
    touchType = -1;
	self.backgroundColor = [UIColor clearColor];
}

- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event {
	touchType = -1;
	self.backgroundColor = [UIColor clearColor];
	/*
    if(self.superview){
        [self.superview touchesMoved:touches withEvent:event];
	}
	*/
}
    
@end

@implementation ThreadViewController

@synthesize board;
@synthesize thread_id;
@synthesize post_id;

@synthesize disappear;

@synthesize contentView;
@synthesize webView;


- (id)init{
    if( (self=[super init]) != nil ){
        smth = [[NewSMTH alloc] init];
    }
    return self;
}

-(void) setThreadViewWithTitle:(NSString*)title 
                         board:(Board*)b 
                     thread_id:(NSInteger*)tid
                       post_id:(NSInteger*)pid{
    [self setTitle:title];
    //self.navigationController.navigationBar.title = title;
    [self setBoard:b];
    [self setThread_id:tid];
    [self setPost_id:pid];
}

// Implement loadView to create a view hierarchy programmatically.
- (void)loadView {
    NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
    
    self.navigationController.navigationBar.barStyle = UIBarStyleBlackTranslucent;
    
    CGRect rect = [[UIScreen mainScreen] applicationFrame];
    
    contentView = [[[UIView alloc] initWithFrame:rect] autorelease];
    //contentView.backgroundColor = [UIColor blackColor];
    contentView.autoresizesSubviews = YES;
    contentView.autoresizingMask = (UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight);
    contentView.multipleTouchEnabled = YES;
    
    //self.multipleTouchEnabled = YES;
    //self.navigationController.navigationBar.
    
    webView = [[[UIWebView alloc] initWithFrame:rect] autorelease];
    webView.backgroundColor = [UIColor blackColor];
    
    webView.multipleTouchEnabled = YES;
    webView.exclusiveTouch = NO;
    [webView setUserInteractionEnabled:YES];
    
    //webView.scalesPageToFit = YES;
    contentView.autoresizingMask = UIViewAutoresizingFlexibleWidth;
    [contentView addSubview:webView];
    //[webView loadHTMLString:@"<html><body style='background-color: #222;'></body></html>" baseURL:[NSURL URLWithString:@"http://ipsmth.appspot.com/vp/"]];
    
    /*
    ThreadTransparentView *leftTransparentView = [[[ThreadTransparentView alloc] initWithFrame:rect] autorelease];
    leftTransparentView.controller = self;
    leftTransparentView.tag = kleftTransparentView;
    //leftTransparentView.backgroundColor = [UIColor orangeColor];
    [leftTransparentView setUserInteractionEnabled:YES];
    [contentView addSubview:leftTransparentView];
    
    ThreadTransparentView *rightTransparentView = [[[ThreadTransparentView alloc] initWithFrame:rect] autorelease];
    rightTransparentView.controller = self;
    rightTransparentView.tag = krightTransparentView;
    //rightTransparentView.backgroundColor = [UIColor orangeColor];
    [rightTransparentView setUserInteractionEnabled:YES];
    [contentView addSubview:rightTransparentView];
    */
    
    ThreadTransparentView *centerTransparentView = [[[ThreadTransparentView alloc] initWithFrame:rect] autorelease];
    centerTransparentView.controller = self;
    centerTransparentView.tag = kcenterTransparentView;
    //centerTransparentView.backgroundColor = [UIColor orangeColor];
    [centerTransparentView setUserInteractionEnabled:YES];
    [contentView addSubview:centerTransparentView];
    
    
    /*
     rect.origin.x = rect.origin.y = 0.0f;
     textView = [[UITextView alloc] initWithFrame:rect];
     
     textView.editable = NO;
     textView.textAlignment = UITextAlignmentLeft;
     textView.font = [UIFont fontWithName:@"American Typewriter" size:20];
     textView.backgroundColor = [UIColor whiteColor];
     
     [contentView addSubview:textView];
     [textView release];
     */
    
    
    self.view = contentView;
    
    //[self loadToolbar];
    
    rect = [[UIScreen mainScreen] applicationFrame];
    activityIndicator = [[UIActivityIndicatorView alloc] initWithFrame:CGRectMake(0.0f, 0.0f, 32.0f, 32.0f)];
    [activityIndicator setCenter:CGPointMake(rect.size.width/2, rect.size.height/2-20)];
    [activityIndicator setActivityIndicatorViewStyle:UIActivityIndicatorViewStyleGray];
    [self.view addSubview:activityIndicator];
    
    //self.navigationController.navigationBar.barStyle = UIBarStyleBlackTranslucent;
    
    [self setViewsRotation];
    
    [pool release];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    self.disappear=0;
    [self setViewsRotation];
    //[self hideToolbarAndNavBar];
}

- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
    [self loadPostViewAsynchronously];
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    self.disappear=1;
    [webView loadHTMLString:@"<html><head></head><body></body></html>" baseURL:[NSURL URLWithString:@"http://ipsmth.appspot.com/vp/"]];
}
- (void)viewDidDisappear:(BOOL)animated {
    [super viewDidDisappear:animated];
}

- (void) setViewsRotation {
    //UIToolbar *toolbar = (UIToolbar*)[self.view viewWithTag:TOOLBAR_VIEW];
	
    //ThreadTransparentView *leftTransparentView = (ThreadTransparentView*)[self.view viewWithTag:kleftTransparentView];
    //ThreadTransparentView *rightTransparentView = (ThreadTransparentView*)[self.view viewWithTag:krightTransparentView];
    ThreadTransparentView *centerTransparentView = (ThreadTransparentView*)[self.view viewWithTag:kcenterTransparentView];
    
    UIInterfaceOrientation orientation = self.interfaceOrientation;
    if(orientation==UIInterfaceOrientationLandscapeLeft || orientation==UIInterfaceOrientationLandscapeRight){
        //[contentView setFrame:CGRectMake(0.0f, 0.0f, 480.0f, 300.0f)];
        [webView setFrame:CGRectMake(0.0f, 0.0f, 480.0f, 300.0f)];
        //[leftTransparentView setFrame:CGRectMake(0.0f, 0.0f, 40.0f, 300.0f)];
        //[rightTransparentView setFrame:CGRectMake(440.0f, 0.0f, 40.0f, 300.0f)];
        [centerTransparentView setFrame:CGRectMake(225.0f, 0.0f, 30.0f, 300.0f)];
        //[toolbar setFrame:CGRectMake(0.0f, 300.0f-44.0f, 480.0f, 44.0f)];
        [activityIndicator setCenter:CGPointMake(240, 140)];
    }else{
        //[contentView setFrame:CGRectMake(0.0f, 0.0f, 320.0f, 460.0f)];
        [webView setFrame:CGRectMake(0.0f, 0.0f, 320.0f, 460.0f)];
        //[leftTransparentView setFrame:CGRectMake(0.0f, 0.0f, 40.0f, 460.0f)];
        //[rightTransparentView setFrame:CGRectMake(280.0f, 0.0f, 40.0f, 460.0f)];
        [centerTransparentView setFrame:CGRectMake(145.0f, 0.0f, 30.0f, 460.0f)];
        //[toolbar setFrame:CGRectMake(0.0f, 460.0f-44.0f, 320.0f, 44.0f)];
        [activityIndicator setCenter:CGPointMake(160, 235)];
    }
    //[self.view bringSubviewToFront: toolbar];
    //[self.view bringSubviewToFront: activityIndicator];
    [self.view bringSubviewToFront: centerTransparentView];
}

-(void) loadFollowingPosts {
    Post *post = [smth getPostWithBoardId:[self.board bid] post_id:self.post_id post_type:@"thread_next"];
    //while(post && [post pid]!=self.post_id){
    while(self.disappear==0 && post && [post tid]==self.thread_id && [post pid]!=self.post_id){
        NSString *content = [[post content] stringByReplacingOccurrencesOfString:@"\\" withString:@"\\\\"];
        content = [content stringByReplacingOccurrencesOfString:@"\n" withString:@"\\n"];
        content = [content stringByReplacingOccurrencesOfString:@"'" withString:@"\\'"];
        
        NSString *jsCommand = [NSString stringWithFormat:@"appendToBody('%@');", content];
        //NSString *jsCommand = [NSString stringWithFormat:@"appendToBody('<hr/><div onclick='toggleHead(\"Post_%d\")'><span class='title'>%@</span></div>%@');", [post pid], [post title], content];
        
        [self.webView stringByEvaluatingJavaScriptFromString:jsCommand];
        [self setPost_id:[post pid]];
        
        /*
        UIAlertView *alert = [[[UIAlertView alloc] initWithTitle:@"Debug 8"
                                                     message:result
                                                    delegate:nil
                                           cancelButtonTitle:@"Dismiss"
                                           otherButtonTitles:nil] autorelease];
        [alert show];
        */
        if(self.disappear==0){
            post = [smth getPostWithBoardId:[self.board bid] post_id:self.post_id post_type:@"thread_next"];
        }else{
            break;
        }
    }
    
}

-(void) loadPostViewData:(id)object{
    NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
    
    Post *post = [smth getPostWithBoardId:[self.board bid] post_id:self.thread_id post_type:@"no"];
	
	[self performSelectorOnMainThread:@selector(stopAnimating) withObject:nil waitUntilDone:NO];
	if(post){
        [self setPost_id:[post pid]];
        //[self setTitle:[post title]];
		[self performSelectorOnMainThread:@selector(setTitle:) withObject:[post title] waitUntilDone:NO];
		
        //NSLog([post content]);
		
		NSString *css = [smth getCssStyle];
		NSString *script = @"<script type='text/javascript'>\nfunction appendToBody(html){var div_node=document.createElement('div');div_node.innerHTML=html;document.body.appendChild(div_node);}\n</script>";
		NSString *html = [NSString stringWithFormat:@"<html><head><style>%@</style>%@</head><body><div>%@</div></body></html>", css, script, [post content]];
		//NSString *html = [NSString stringWithFormat:@"<html><head>%@\n%@</head><body><div><hr/><div onclick='toggleHead(\"Post_%d\")'><span class='title'>%@</span></div>%@</div></body></html>", css, script, [post pid], [post title], [post content]];
		//NSLog(html);
		
        [self.webView loadHTMLString:html baseURL:[NSURL URLWithString:@"http://ipsmth.appspot.com/vp/"]];
        
        /**************************************************************************************************************
        NSString *url = [NSString stringWithFormat:@"http://ipsmth.appspot.com/vp/thread/?board_id=%d&thread_id=%d", [self.board bid], self.thread_id];
        NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:url] 
                                                 cachePolicy:NSURLRequestReturnCacheDataElseLoad
                                             timeoutInterval:60.0];
        [self.webView loadRequest:request]
        **************************************************************************************************************/
        
        [self loadFollowingPosts];
    }
    
	[pool release];
}

-(void) loadPostViewAsynchronously{
	[self startAnimating];
    [self performSelectorInBackground:@selector(loadPostViewData:) withObject:nil];
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
    return YES;
}

- (void) willAnimateSecondHalfOfRotationFromInterfaceOrientation:(UIInterfaceOrientation) fromOrientation duration:(NSTimeInterval) duration{
    [self setViewsRotation];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}

- (void) startAnimating{
	NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
	[activityIndicator startAnimating];
	[pool release];
}

- (void) stopAnimating{
	NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
	[activityIndicator stopAnimating];
	[pool release];
}

- (void)toggleToolbarAndNavBar {
    UINavigationBar *navBar = self.navigationController.navigationBar;
    navBar.hidden = !navBar.hidden;
    //UIToolbar *toolbar = (UIToolbar*)[self.view viewWithTag:TOOLBAR_VIEW];
    //toolbar.hidden = !toolbar.hidden;
}

-(void) hideToolbarAndNavBar {
    UINavigationBar *navBar = self.navigationController.navigationBar;
    navBar.hidden = YES;
    //UIToolbar *toolbar = (UIToolbar*)[self.view viewWithTag:TOOLBAR_VIEW];
    //toolbar.hidden = YES;
}

- (void)dealloc {
    [contentView release];
    [webView release];
	[activityIndicator release];
    [board release];
    [smth release];
    [super dealloc];
}


@end
